package reflect;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author wangyingjie
 * @date
 * @remark 用反射构造对象池
 */
public class ObjectPoolFactory {

    private Map<String,Object> objPool = new HashMap<>();

    private Integer age;

    /**
     * 反射创建对象
     * @param className
     * @return
     */
    private Object createObj(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class<?> clazz = Class.forName(className);
        return clazz.newInstance();
    }

    /**
     * 初始化对象池
     * @param fileName
     * @throws IOException
     */
    private void initObjPool(String fileName) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        FileInputStream fis = null;
        try {
            //根据文件名生成输入流
            fis = new FileInputStream(fileName);
            //把输入流中的数据(key-value)加载到properties中，value是类全名
            Properties properties = new Properties();
            properties.load(fis);
            for (Object o : properties.keySet()) {
                String name = (String) o;
                String clazzName = properties.getProperty(name);//value是类全名
                //反射创建对象，放入对象池
                Object obj = createObj(clazzName);
                objPool.put(name,obj);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if (fis!=null)
                    fis.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 从对象池中拿对象
     * @param objName
     * @return
     */
    private Object getObj(String objName){
        return objPool.get(objName);
    }

    public static void main(String[] args) throws IllegalAccessException, ClassNotFoundException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        ObjectPoolFactory objPool = new ObjectPoolFactory();
        objPool.initObjPool("D:\\pp\\effective-java\\resource\\obj.properties");
        Object a = objPool.getObj("a");
        System.out.println(a);
//        Class<?> clazz = Class.forName("javax.swing.JFrame");
//        Constructor<?> constructor = clazz.getConstructor(String.class);
//        Object o = constructor.newInstance("测试窗口");
//        System.out.println(o);
    }
}
